#include <IRremote.h>
#define IR_RECEIVE_PIN  3  //定义红外接收模块的引脚 
IRrecv IrReceiver(IR_RECEIVE_PIN);
decode_results results;
int ir_val;
int ir_FFFF;
int ir_val_data;
#define INA 7  //定义引脚控制左边电机方向
#define ENA 6  //控制左边电机速度
#define INB 8  //右边电机方向
#define ENB 5  //右边电机速度

void setup() {
  Serial.begin(115200);  //这里定义串口波特率为115200
  Serial.println("Enabling IRin");
  IrReceiver.enableIRIn();  // Start the receiver
  //IrReceiver.blink13(true); // Enable feedback LED

  Serial.print(F("Ready to receive IR signals at pin "));
  Serial.println(IR_RECEIVE_PIN);
  pinMode(INA, OUTPUT);  //设置控制电机的引脚为输出模式
  pinMode(ENA, OUTPUT);
  pinMode(INB, OUTPUT);
  pinMode(ENB, OUTPUT);
}

void loop() {
  if(IrReceiver.decode(&results))
  {
    ir_val = results.value;
    //IrReceiver.printResultShort(&Serial);
    Serial.println(ir_val,HEX);
    if(ir_val == 0xFFFF)
    {
      ir_FFFF = ir_val;
    }
    else
    {
      ir_val_data = ir_val;
    }
    switch(ir_val_data)
    {
      case 0x18E7: car_forward(); break;  //小蜗牛前进
      case 0x4AB5: car_back(); break;     //小蜗牛后退
      case 0x10EF: car_left(); break;     //小蜗牛左旋转
      case 0x5AA5: car_right(); break;    //小蜗牛右旋转
    }
    IrReceiver.resume(); // Receive the next value
  }
  else
  {
    car_stop(); //小蜗牛停止
  }
  delay(100);
}

//小蜗牛前进
void car_forward()
{
  digitalWrite(INA, HIGH);  //输出高电平，控制左边电机正转
  analogWrite(ENA, 200);    //PWM输出，控制左边电机速度
  digitalWrite(INB, HIGH);  //右边电机正转
  analogWrite(ENB, 200);    //右边电机速度
}
//小蜗牛后退
void car_back()
{
  digitalWrite(INA, LOW);  //左边反转
  analogWrite(ENA, 200);   //左边速度
  digitalWrite(INB, LOW);  //右边反转
  analogWrite(ENB, 200);   //右边速度
}
//小蜗牛左旋转
void car_left()
{
  digitalWrite(INA, LOW);
  analogWrite(ENA, 200);
  digitalWrite(INB, HIGH);
  analogWrite(ENB, 200);
}
//小蜗牛右旋转
void car_right()
{
  digitalWrite(INA, HIGH);
  analogWrite(ENA, 200);
  digitalWrite(INB, LOW);
  analogWrite(ENB, 200);
}
//停止
void car_stop()
{
  digitalWrite(INA, HIGH);
  analogWrite(ENA, 0);
  digitalWrite(INB, HIGH);
  analogWrite(ENB, 0);
}
